import tkinter as tk
from tkinter import messagebox, filedialog
import os
import datetime
import winreg
import subprocess

# 配置文件路径
CONFIG_FILE = "config.txt"

# 读取配置文件获取保存路径
def read_config():
    global BASE_SAVE_PATH
    if os.path.exists(CONFIG_FILE):
        with open(CONFIG_FILE, "r") as f:
            path = f.read().strip()
            if path:
                BASE_SAVE_PATH = path

# 保存配置文件并隐藏
def save_config():
    with open(CONFIG_FILE, "w") as f:
        f.write(BASE_SAVE_PATH)
    # 设置文件为隐藏属性
    try:
        subprocess.run(f'attrib +h {CONFIG_FILE}', shell=True, check=True)
    except subprocess.CalledProcessError:
        messagebox.showerror("错误", "设置配置文件隐藏属性失败")

# 全局变量
BASE_SAVE_PATH = os.getcwd()
HISTORY = []
SERIAL_NUMBER = 1

# 读取配置
read_config()

def get_current_date_folder():
    now = datetime.datetime.now()
    year_folder = str(now.year)
    month_folder = str(now.month).zfill(2)
    folder_path = os.path.join(BASE_SAVE_PATH, year_folder, month_folder)
    if not os.path.exists(folder_path):
        os.makedirs(folder_path)
    return folder_path

def save_to_file(barcode, result):
    global SERIAL_NUMBER
    date_folder = get_current_date_folder()
    now = datetime.datetime.now()
    timestamp = now.strftime("%Y-%m-%d %H:%M:%S")
    file_name = now.strftime("%y%m%d.csv")
    file_path = os.path.join(date_folder, file_name)
    is_new_file = not os.path.exists(file_path)
    with open(file_path, "a", encoding="utf-8-sig") as f:
        if is_new_file:
            f.write("序号,时间,条码,判断结果\n")
        f.write(f"{SERIAL_NUMBER},{timestamp},{barcode},{result}\n")
    SERIAL_NUMBER += 1

def add_to_history(barcode, result):
    global HISTORY
    HISTORY.append((barcode, result))
    if len(HISTORY) > 10:
        HISTORY.pop(0)
    history_text.delete(1.0, tk.END)
    for i, (barcode, result) in enumerate(reversed(HISTORY), start=1):
        history_text.insert(tk.END, f"{len(HISTORY) - i + 1}. 条码: {barcode}, 结果: {result}\n")

def on_barcode_enter(event=None):
    barcode = barcode_entry.get().strip()
    if barcode:
        barcode_entry.barcode = barcode
        result_entry.focus_set()

def on_result_enter(event=None):
    result = result_entry.get().strip()
    barcode = getattr(barcode_entry, 'barcode', '')
    if barcode and result in ['00', '01']:
        result_text = "OK" if result == '01' else "NG"
        save_to_file(barcode, result_text)
        add_to_history(barcode, result_text)
        result_entry.delete(0, tk.END)
        barcode_entry.delete(0, tk.END)
        barcode_entry.focus_set()

def set_save_path():
    global BASE_SAVE_PATH
    path = filedialog.askdirectory()
    if path:
        BASE_SAVE_PATH = path
        save_path_label.config(text=f"保存路径: {BASE_SAVE_PATH}")
        save_config()

def open_record_folder():
    date_folder = get_current_date_folder()
    if os.path.exists(date_folder):
        try:
            if os.name == 'nt':  # Windows 系统
                os.startfile(date_folder)
            elif os.name == 'posix':  # Linux 或 macOS 系统
                subprocess.Popen(['xdg-open', date_folder])
        except Exception as e:
            messagebox.showerror("错误", f"打开文件夹失败: {e}")
    else:
        messagebox.showinfo("提示", "记录文件夹不存在。")

# 创建主窗口
root = tk.Tk()
root.title("扫码记录系统")

# 扫码输入框
barcode_label = tk.Label(root, text="扫码:")
barcode_label.pack()
barcode_entry = tk.Entry(root)
barcode_entry.pack()
barcode_entry.bind("<Return>", on_barcode_enter)
barcode_entry.focus_set()

# 判断结果输入框
result_label = tk.Label(root, text="判断结果 (01: OK, 00: NG):")
result_label.pack()
result_entry = tk.Entry(root)
result_entry.pack()
result_entry.bind("<Return>", on_result_enter)

# 历史记录显示
history_label = tk.Label(root, text="历史记录:")
history_label.pack()
history_text = tk.Text(root, height=10, width=50)
history_text.pack()

# 功能按钮
function_frame = tk.Frame(root)
function_frame.pack(pady=10)

save_path_button = tk.Button(function_frame, text="设置保存路径", command=set_save_path)
save_path_button.pack(side=tk.LEFT, padx=5)

open_folder_button = tk.Button(function_frame, text="打开记录文件夹", command=open_record_folder)
open_folder_button.pack(side=tk.LEFT, padx=5)

# 保存路径显示
save_path_label = tk.Label(root, text=f"保存路径: {BASE_SAVE_PATH}")
save_path_label.pack()

# 运行主循环
root.mainloop()
